#include <iostream>
#include <vector>
#include <queue>
#include <unordered_map>
using namespace std;

int m, n;

int bing[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
int ma[8][2] = {{-2, 1}, {-1, 2}, {1, 2},   {2, 1},
                {2, -1}, {1, -2}, {-1, -2}, {-2, -1}};

vector<vector<vector<int>>> memo;
vector<vector<bool>> vi;

struct State {
    int x, y, z;
    State(int a, int b, int c) : x(a), y(b), z(c) {}
};

struct myhash {
    size_t operator()(const State& s) const {
        return hash<int>()(s.x ^ s.y ^ s.z);
    }
};

int main() {
    cin >> m >> n;
    vector<string> matrix(m);
    for (int i = 0; i < m; i++) cin >> matrix[i];

    queue<State> que;
    unordered_map<State, bool, myhash> vi;
    vi[{0, 0, 0}] = 1;
    que.emplace(0, 0, 0);
    int step = 0;

    while (!que.empty()) {
        int sz = que.size();
        for (int i = 0; i < sz; i++) {
            State fr = que.front();
            que.pop();
            if (fr.x == m - 1 && fr.y == n - 1) return step;
            if (matrix[fr.x][fr.y] == '.') {
                if (fr.z == 0) {
                    for (int j = 0; j < 4; j++) {
                        int fx = fr.x + bing[j][0];
                        int fy = fr.y + bing[j][1];
                        if (fx >= 0 && fx < m && fy >= 0 && fy < n &&
                            matrix[fx][fy] != 'X' && !vi[{fx, fy, 0}])
                            que.emplace(fx, fy, 0);
                    }
                } else if (fr.z == 1) {
                    for (int j = 0; j < 8; j++) {
                        int fx = fr.x + ma[j][0];
                        int fy = fr.y + ma[j][1];
                        if (fx >= 0 && fx < m && fy >= 0 && fy < n &&
                            matrix[fx][fy] != 'X' && !vi[{fx, fy, 0}])
                            que.emplace(fx, fy, 1);
                    }
                } else {
                    cout << "wrong1" << endl;
                }
            } else if (matrix[fr.x][fr.y] == 'S') {
                if (fr.z == 0) {
                } else if (fr.z == 1) {
                } else {
                    cout << "wrong2" << endl;
                }
            } else {
                cout << "wrong" << endl;
            }
        }
        step++;
    }

    return 0;
}

/*
9 9
.........
.....XXX.
.....X.X.
.....X.X.
.....X.XS
XXXXXX.XX
.........
.........
.........


*/